package com.kusej.gitmanger.utils;

import com.google.common.collect.Maps;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.Map;
import java.util.Set;

public class LoadUtils {
    private static final Map<String, ProgressIndicator> indicator = Maps.newConcurrentMap();
    private static final int fractionCount = 10;

    public static void defaultLoading(Project project, String title) {
//        loading(project, title, 1000L);
//   todo 目前看load不起作用
    }

    public static void loading(Project project, String title, long time) {
        ProgressManager.getInstance().run(new Task.Backgroundable(project, title, true) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                // 模拟加载过程
                try {
                    LoadUtils.indicator.put(title, indicator);
                    for (int i = 0; i < fractionCount; i++) {
                        // 检查加载页是否被取消
                        if (indicator.isCanceled()) {
                            indicator.stop();
                            return;
                        }
                        // 设置进度条的进度
                        indicator.setFraction((double) i / fractionCount);
                        Thread.sleep(time / fractionCount);
                    }

                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        });

    }

    // 在需要的时候调用该方法关闭加载页
    public static void closeLoading() {
//        Set<String> threads = indicator.keySet();
//        for (String t : threads
//        ) {
//            if (indicator.get(t) != null) {
//                indicator.get(t).cancel();
//            }
//        }
//        indicator.clear();
        LocalFileSystem.getInstance().refresh(true);
    }
}
